--
-- Author: shunguo.chen
-- Date: 2016-06-20 12:38:27
--
-- MailModel

local MailVo = import(".MailVo")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ModelBase)

local QUERY_START_NUM = 100
local QUERY_PER_NUM = 20

function ClassRef:ctor(data)
	self.super.ctor(self, data)
end

function ClassRef:init()
	-- 邮件最大数
	self._mailMaxNum = nil
	-- 未读邮件
	self._mailUnreadNum = 0
	-- 未拉取的新邮件
	self._mailNewNum = 0
	self._mails = nil

	self._removeCron = nil

	self._isInReqMails = false
end

function ClassRef:getMails(cb)
	local reqType
	if self._mails == nil then
		self._mails = {}
		reqType = 0
	else
		--拉取新邮件
		if self._mailNewNum > 0 then
			reqType = 1
		end
	end
	if reqType then
		self:queryMails(reqType, cb)
	else
		executeFunc(cb, table.clone(self._mails))
	end
end

function ClassRef:unreadNumChange(num)
	if self._mailUnreadNum ~= num then
		if self._mailUnreadNum < num then
			UIHandler:showThirdLevelTips({remindId=Constant.FUNC_TYPE_MAIL})
		end

		self._mailUnreadNum = num

		-- print("MailModel._mailUnreadNum = " .. self._mailUnreadNum)
		-- print("MailModel._mailMaxNum = " .. tostring(self._mailMaxNum))
		-- print("MailModel._mailNewNum = " .. self._mailNewNum)
	end

	self:updateMailNewPoint()
end

function ClassRef:updateMailNewPoint()
	if UD.badge:setNum(Constant.FUNC_TYPE_MAIL, self._mailUnreadNum) then
		-- UD.dirty = true
	end
end


-- 删除过期邮件，并添加cron删除下一封最快过期的邮件
function ClassRef:removeExpiredMails()
	if not self._mails or #self._mails == 0 then return end
	if self._removeCron then
		scheduler.cancelCron(self._removeCron)
	end

	local mails = {}
	local minGap = 2^53
	local delUids = {}
	for i,v in ipairs(self._mails) do
		local isExpired, gap = v:isExpired()
		if not isExpired then
			mails[#mails + 1] = v
			minGap = math.min(minGap, gap)
		else
			delUids[#delUids + 1] = v.uid
		end
	end

	-- 有到期邮件，删除
	if #delUids > 0 then
		app:sendMsg("MailController", "mailDelete", delUids)
	end

	-- 最短间隔之后再执行删除操作
	self._mails = mails
	if #self._mails > 0 then
		self._removeCron = scheduler.newCron(handler(self, self.removeExpiredMails), minGap)
	end
end

function ClassRef:onMailNotice(ret)
	-- dump(ret, "MailModel:onMailNotice() ret")
	if ret.newNum > 0 then
		if self._mailMaxNum then
			self._mailMaxNum = self._mailMaxNum + math.max(ret.newNum - self._mailUnreadNum, 0)
			self._mailNewNum = self._mailNewNum + math.max(ret.newNum - self._mailUnreadNum, 0)
		end
		self:unreadNumChange(ret.newNum)
	else
		self:unreadNumChange(0)
	end
end

function ClassRef:onQueryMails(ret)
	-- dump(ret, "MailModel:queryMails() ret")
	self._isInReqMails = false

	if self._reqType ~= 2 then
		self._mailNewNum = 0
		-- print("MailModel._mailNewNum = " .. self._mailNewNum)
	end
	
	self._mailMaxNum = ret.total or 0
	-- print("MailModel._mailMaxNum = " .. tostring(self._mailMaxNum))

	if ret.mails then
		local newMails = {}
		for i,v in ipairs(ret.mails) do
			local mail = MailVo.new(v)
			if self._reqType == 1 then
				table.insert(self._mails, i, mail)
			else
				table.insert(self._mails, mail)
			end
			newMails[i] = mail
		end

		self:removeExpiredMails()

		if self._reqCB then
			self._reqCB(table.clone(self._mails))
			self._reqCB = nil
		else
			if #newMails > 0 then
				app:sendMsg("MailController", "appendMails", newMails, self._reqType == 1)
			end
		end
	end
end

function ClassRef:onQueryMailDetail(ret)
	-- dump(ret, "MailModel:queryMailDetail() recv", 5)
	local tarMail
	for i,mail in ipairs(self._mails) do
		if mail.uid == ret.mail.uid then
			if mail:isNew() then
				self:unreadNumChange(math.max(self._mailUnreadNum - 1, 0))
			end
			tarMail = MailVo.new(ret.mail)
			tarMail:setGetDetail(true)
			self._mails[i] = tarMail
			break
		end
	end
	app:sendMsg("MailController", "mailUpdate", tarMail)
end

function ClassRef:onDeleteMail(ret)
	local uids = self._deleteUids
	self._deleteUids = nil

	if ret.ok then
		for i=#self._mails,1,-1 do
			local mail = self._mails[i]
			if table.indexof(uids, mail.uid) then
				table.remove(self._mails, i)
			end
		end
		self._mailMaxNum = self._mailMaxNum - #uids
		app:sendMsg("MailController", "mailDelete", uids)

		if #self._mails == 0 then
			--删除之后 本地邮件＝0，再拉取一次
			self:queryMails(0)
		end
	end
end

function ClassRef:onTakeMailItems(ret)
	-- dump(ret, "mail.C2S_TakeMailItems")
	if ret.uids then
		local autoDeleteUids = {}
		for i,mail in ipairs(self._mails) do
			if table.indexof(ret.uids, mail.uid) then
				if mail:isNew() then
					self:unreadNumChange(math.max(self._mailUnreadNum - 1, 0))
				end
				mail.status = Enums.MailStatus.fetch
				mail.canDelete = true
				mail.hasAttachment = false

				if mail:isAutoDelete() then
					autoDeleteUids[#autoDeleteUids + 1] = mail.uid
				else
					app:sendMsg("MailController", "mailUpdate", mail)
				end
			end
		end

		-- 自动删除的邮件
		if #autoDeleteUids > 0 then
			self._deleteUids = autoDeleteUids
			self:onDeleteMail({ok=true})
		end
	end

	-- if ret.err and ret.err ~= "" then
	-- 	local msgConfig = GD:getMessageConfig(ret.err)
	-- 	local msgType = msgConfig and tonumber(msgConfig.type) or 2
 --    	local message = msgConfig and L(msgConfig.msgId) or L(ret.err)
	-- 	if msgType == 1 then
 --            display.pushToast(message)
 --        else
 --            local messageBox = display.newMessageBox(message)
 --            UIHandler:addPopDialog(messageBox)
 --        end
	-- end
end

----------------------------------------- request ------------------------------------
-- reqType = 0(从第一开始拉),1(拉取最新的),2(拉取以前的)
-- cb 	请求回调
function ClassRef:queryMails(reqType, cb)
	reqType = reqType or 0
	if self._isInReqMails then return end

	local len = #self._mails
	local param
	if reqType == 0 then
		param = {begin=0, count=QUERY_START_NUM}
	elseif reqType == 1 then
		if self._mailNewNum > 0 then 
			param = {begin=0, count=self._mailNewNum}
		end
	else
		if self._mailMaxNum and (len + self._mailNewNum) < self._mailMaxNum then
			param = {begin=len + self._mailNewNum, count=QUERY_PER_NUM}
		end
	end
	if param == nil then return end
	-- dump(param, "MailModel:queryMails() param")
	
	self._isInReqMails = true
	self._reqType = reqType
	self._reqCB = cb
	app.session:request("pb_mail.C2S_QueryMails", param)
end

function ClassRef:queryMailDetail(uid)
	app.session:request("pb_mail.C2S_QueryMailDetail", {uid=uid})
end

function ClassRef:deleteMail(uid)
	if self._deleteDialog then return end
	-- print("MailModel:deleteMail uid = " .. tostring(uid))
	local uids = {}
	if uid then
		uids[1] = uid
	else
		for i,mail in ipairs(self._mails) do
			if mail:canDeleted() then
				uids[#uids + 1] = mail.uid
			end
		end
	end
	if #uids == 0 then
		display.pushToast(L("tips_1150002"))
		return
	end

	if self._deleteUids then return end
	self._deleteUids = uids
	-- dump(uids, "MailModel:deleteMail uids")

	local text = (uid==nil) and L("tips_1150004") or L("tips_1150005")
	self._deleteDialog = display.newConfirmDialog(text, 
		function()
			self._deleteDialog = nil
			app.session:request("pb_mail.C2S_DeleteMail", {uids=uids})
		end,
		function() 
			self._deleteDialog = nil
			self._deleteUids = nil
		end)
	UIHandler:addPopDialog(self._deleteDialog)
end

function ClassRef:takeMailsItems(uid)
	local uids = {}
	local hasPresentCoin = false
	if uid then
		uids[1] = uid
		for i,mail in ipairs(self._mails) do
			if mail.uid == uid and mail:hasPresentCoin() then
				hasPresentCoin = true
				break
			end
		end
	else
		for i,mail in ipairs(self._mails) do
			if mail:canGetItems() then
				uids[#uids + 1] = mail.uid
				if mail:hasPresentCoin() then
					hasPresentCoin = true
				end
			end
		end
	end
	if #uids == 0 then
		display.pushToast(L("tips_1150003"))
		return
	end

	-- 有赠送钻石，需要判定是否授权成功
	if hasPresentCoin and not app:isMidasPermissionOK() then
		app:getRunningScene():openMidasPermissionDlg(L("warrantExpired"))
		return
	end

	-- dump(uids, "MailModel:takeMailsItems uids")

	app.session:request("pb_mail.C2S_TakeMailItems",{uids=uids})
end

return ClassRef